//============================================================================
// Name        : TimeMeasurement.cpp
// Author      : lucmir@dcc.ufmg.br
// Description :
//============================================================================


#include "TimeMeasurement.h"


TimeMeasurement::TimeMeasurement() {
	this->clear();
}

TimeMeasurement::~TimeMeasurement() {
}

void TimeMeasurement::clear() {
	this->usrTime = 0.0;
	this->sysTime = 0.0;
	this->totalTime = 0.0;
}

void TimeMeasurement::setUsrTime() {
	struct rusage resources;
	double lastTime = this->usrTime;

	if(getrusage(RUSAGE_SELF, &resources) != 0) {
		perror("ERROR: getrusage failed");
	}
	this->usrTime = (double) resources.ru_utime.tv_sec + 1.e-6 * (double) resources.ru_utime.tv_usec;
	if(lastTime > 0) {
		this->usrTime -= lastTime;
	}
}

void TimeMeasurement::setSysTime() {
	struct rusage resources;
	double lastTime = this->sysTime;

	if(getrusage(RUSAGE_SELF, &resources) != 0) {
		perror("getrusage failed");
	}
	this->sysTime = (double) resources.ru_stime.tv_sec + 1.e-6 * (double) resources.ru_stime.tv_usec;
	if(lastTime > 0) {
		this->sysTime -= lastTime;
	}
}

void TimeMeasurement::setTotalTime() {
	struct timeval tempo;
	double lastTime = this->totalTime;

	if(gettimeofday(&tempo, NULL) != 0) {
		perror("gettimeofday failed");
	}
	this->totalTime = ((double)tempo.tv_sec + 1.e-6 * (double) tempo.tv_sec );
	if(lastTime > 0) {
		this->totalTime -= lastTime;
	}
}

void TimeMeasurement::print() {
	printf("\nTempo consumido: usr:%fs / sis:%fs / tot:%fs\n", this->usrTime, this->sysTime, this->totalTime);
}
